package message.chat;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

/**
 * Servlet implementation class Chat
 */
public class Chat extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Chat() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String university = request.getParameter("university");
		String course = request.getParameter("course");
		String email = request.getParameter("email");
		String courseid = university+""+course;
		
		int cseid = Integer.valueOf(courseid);
		
		System.out.println(university+""+course+""+email+""+courseid+""+cseid);
		
		int[] studentId = getCourseStudents(cseid);
		
		for (int i = 0; i < studentId.length; i++) {
		      roomChat(studentId[i]);
		    } 
		
	}

	private void roomChat(int i) throws SQLException {

		String query = "Select useremail from users where studentid='"+ i +"'";
	    String connectionString = "jdbc:mysql://localhost:3306/yooim";
	    String userName = "root";
	    String password = "mapat";
	    Connection conn = null; 
	    ResultSet rs = null;
	    try {
	    	
	    	Class.forName("com.mysql.jdbc.Driver").newInstance();
	    	conn = DriverManager.getConnection(connectionString,userName,password);
	    	Statement st = conn.createStatement();
	    	rs = st.executeQuery(query);
	    	System.out.println(rs.getFetchSize());
	    	//conn.close();
	    }
	    catch(Exception e)
	    {
	    	System.out.println("Error while connection to DB - validate : "+e.toString());
	    }
	    
	    if(rs != null)
	    {
	    	String mail = rs.getString(1);
	    	
	    	XMPPConnection con = null;
	        try {
	             XMPPConnection.DEBUG_ENABLED = true;
	             ConnectionConfiguration configuration = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
	             con = new XMPPConnection(configuration);
	             con.connect();
	             SASLAuthentication.supportSASLMechanism("PLAIN", 0);
	             con.login("patrick.maniraho@gmail.com", "mapat1234");
	            
	             sendChat(con, mail);

	             
	        } catch (XMPPException e) {
	             //e.printStackTrace();
	             System.out.println("Error in connection");
	        } finally {
	             if (con != null) {
	                  con.disconnect();
	             }
	        }
	    	
	    }
		
	}

	private void sendChat(XMPPConnection con, String mail) {
		
		ChatManager chatmanager = con.getChatManager();
		//Chat newChat = chatmanager.createChat(mail, new MessageListener();

		Chat newChat = chatmanager.createChat("patrick.maniraho@gmail.com", new MessageListener(){
		    
			@Override
			public void processMessage(Chat chat, Message message) {
				// TODO Auto-generated method stub
				System.out.println("Received message: " + message);
				
			}
		});
		
		try {
		    ((Chat) newChat).sendMessage("If you receive this please reply!");
		    Roster roster = con.getRoster();
		    Collection<RosterEntry> entries = roster.getEntries();
		    Collection<RosterGroup> groups = roster.getGroups();
		    System.out.println("groups"+groups);
		    /*for (RosterEntry entry : entries) {
		        System.out.println(entry);
		    }*/
		    for (RosterGroup group : groups) {
		        System.out.println("groups"+group);
		    }

		}
		catch (XMPPException e) {
		    System.out.println("Error Delivering block");
		}

		
		
	}

	private int[] getCourseStudents(int cseid) {
		
		String query = "Select studentid from coursestudents where sccourseid='"+ cseid +"'";
	    String connectionString = "jdbc:mysql://localhost:3306/yooim";
	    String userName = "root";
	    String password = "mapat";
	    Connection conn = null; 
	    ResultSet rs = null;
	    try {
	    	
	    	Class.forName("com.mysql.jdbc.Driver").newInstance();
	    	conn = DriverManager.getConnection(connectionString,userName,password);
	    	Statement st = conn.createStatement();
	    	rs = st.executeQuery(query);
	    	System.out.println(rs.getFetchSize());
	    	//conn.close();
	    }
	    catch(Exception e)
	    {
	    	System.out.println("Error while connection to DB - validate : "+e.toString());
	    }
	    
	    if(rs != null)
	    {
	    	int i =0;
	    	int[] arr = null;
	    	try {
	    		
				while(rs.next())
				{
					arr[i] = rs.getInt(1);
				}
	    		
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("error SQL"+e.toString());

			}
			return arr;
	    }
	    else
	    	return null;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
